package com.powerbank.user.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powerbank.common.entity.*;
import com.powerbank.common.exception.BusinessException;
import com.powerbank.common.result.ResultCode;
import com.powerbank.user.dto.CreatePaymentDTO;
import com.powerbank.user.dto.WalletRechargeDTO;
import com.powerbank.user.dto.WalletWithdrawDTO;
import com.powerbank.user.mapper.*;
import com.powerbank.user.service.PaymentService;
import com.powerbank.user.service.WalletService;
import com.powerbank.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 钱包服务实现类
 */
@Slf4j
@Service
public class WalletServiceImpl implements WalletService {

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private WalletTransactionMapper walletTransactionMapper;

    @Autowired
    private PaymentRecordMapper paymentRecordMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PaymentService paymentService;

    // 最小充值金额
    private static final BigDecimal MIN_RECHARGE_AMOUNT = new BigDecimal("1.00");
    // 最小提现金额
    private static final BigDecimal MIN_WITHDRAW_AMOUNT = new BigDecimal("10.00");
    // 单日最大提现金额
    private static final BigDecimal MAX_DAILY_WITHDRAW = new BigDecimal("5000.00");

    @Override
    public WalletInfoVO getUserWallet(Long userId) {
        log.info("获取用户{}钱包信息", userId);

        UserWallet wallet = getOrCreateUserWallet(userId);
        
        WalletInfoVO vo = new WalletInfoVO();
        BeanUtils.copyProperties(wallet, vo);
        vo.setWalletId(wallet.getId());
        vo.setAvailableBalance(wallet.getBalance().subtract(wallet.getFrozenAmount()));
        vo.setWalletStatusDesc(getWalletStatusDesc(wallet.getWalletStatus()));
        vo.setHasPayPassword(wallet.getHasPayPassword() == 1);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentResultVO createRechargeOrder(Long userId, WalletRechargeDTO rechargeDTO) {
        log.info("用户{}创建钱包充值订单 - 金额: {}, 支付方式: {}", 
                userId, rechargeDTO.getAmount(), rechargeDTO.getPaymentMethod());

        // 1. 验证充值金额
        if (rechargeDTO.getAmount().compareTo(MIN_RECHARGE_AMOUNT) < 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), 
                    "充值金额不能少于" + MIN_RECHARGE_AMOUNT + "元");
        }

        // 2. 确保用户钱包存在
        getOrCreateUserWallet(userId);

        // 3. 创建虚拟订单（用于充值）
        RentalOrder virtualOrder = createVirtualRechargeOrder(userId, rechargeDTO.getAmount());

        // 4. 创建支付订单
        CreatePaymentDTO paymentDTO = new CreatePaymentDTO();
        paymentDTO.setOrderId(virtualOrder.getId());
        paymentDTO.setPaymentType("RECHARGE");
        paymentDTO.setPaymentMethod(rechargeDTO.getPaymentMethod());
        paymentDTO.setPaymentAmount(rechargeDTO.getAmount());
        paymentDTO.setClientIp(rechargeDTO.getClientIp());
        paymentDTO.setRemark("钱包充值");

        return paymentService.createPayment(userId, paymentDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processRechargeSuccess(String paymentNo) {
        log.info("处理充值成功回调 - 支付流水号: {}", paymentNo);

        // 1. 获取支付记录
        LambdaQueryWrapper<PaymentRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentRecord::getPaymentNo, paymentNo)
                .eq(PaymentRecord::getPaymentType, "RECHARGE")
                .eq(PaymentRecord::getPaymentStatus, 1); // 已支付
        PaymentRecord paymentRecord = paymentRecordMapper.selectOne(wrapper);

        if (paymentRecord == null) {
            log.warn("未找到对应的充值支付记录: {}", paymentNo);
            return false;
        }

        // 2. 检查是否已处理
        LambdaQueryWrapper<WalletTransaction> txnWrapper = new LambdaQueryWrapper<>();
        txnWrapper.eq(WalletTransaction::getPaymentRecordId, paymentRecord.getId());
        long count = walletTransactionMapper.selectCount(txnWrapper);
        if (count > 0) {
            log.info("充值已处理过，跳过 - 支付流水号: {}", paymentNo);
            return true;
        }

        // 3. 增加钱包余额
        UserWallet wallet = getOrCreateUserWallet(paymentRecord.getUserId());
        BigDecimal balanceBefore = wallet.getBalance();
        BigDecimal balanceAfter = balanceBefore.add(paymentRecord.getActualAmount());

        wallet.setBalance(balanceAfter);
        wallet.setTotalRecharge(wallet.getTotalRecharge().add(paymentRecord.getActualAmount()));
        wallet.setLastTransactionTime(LocalDateTime.now());
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        // 4. 记录钱包交易
        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransactionNo(generateTransactionNo());
        transaction.setUserId(paymentRecord.getUserId());
        transaction.setWalletId(wallet.getId());
        transaction.setTransactionType("RECHARGE");
        transaction.setAmount(paymentRecord.getActualAmount());
        transaction.setBalanceBefore(balanceBefore);
        transaction.setBalanceAfter(balanceAfter);
        transaction.setOrderId(paymentRecord.getOrderId());
        transaction.setOrderNo(paymentRecord.getOrderNo());
        transaction.setPaymentRecordId(paymentRecord.getId());
        transaction.setTransactionStatus(1); // 成功
        transaction.setDescription("钱包充值");
        transaction.setCreatedTime(LocalDateTime.now());
        transaction.setUpdatedTime(LocalDateTime.now());
        walletTransactionMapper.insert(transaction);

        log.info("充值处理成功 - 用户: {}, 充值金额: {}, 余额: {} -> {}", 
                paymentRecord.getUserId(), paymentRecord.getActualAmount(), balanceBefore, balanceAfter);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WalletWithdrawResultVO applyWithdraw(Long userId, WalletWithdrawDTO withdrawDTO) {
        log.info("用户{}申请提现 - 金额: {}, 提现方式: {}", 
                userId, withdrawDTO.getAmount(), withdrawDTO.getWithdrawMethod());

        // 1. 验证提现金额
        if (withdrawDTO.getAmount().compareTo(MIN_WITHDRAW_AMOUNT) < 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), 
                    "提现金额不能少于" + MIN_WITHDRAW_AMOUNT + "元");
        }

        // 2. 验证支付密码
        if (!verifyPayPassword(userId, withdrawDTO.getPayPassword())) {
            throw new BusinessException(ResultCode.PASSWORD_ERROR);
        }

        // 3. 检查钱包余额
        UserWallet wallet = getOrCreateUserWallet(userId);
        BigDecimal availableBalance = wallet.getBalance().subtract(wallet.getFrozenAmount());
        if (availableBalance.compareTo(withdrawDTO.getAmount()) < 0) {
            throw new BusinessException(ResultCode.BALANCE_NOT_ENOUGH);
        }

        // 4. 检查单日提现限额
        checkDailyWithdrawLimit(userId, withdrawDTO.getAmount());

        // 5. 冻结提现金额
        wallet.setFrozenAmount(wallet.getFrozenAmount().add(withdrawDTO.getAmount()));
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        // 6. 计算手续费和实际到账金额
        BigDecimal fee = calculateWithdrawFee(withdrawDTO.getAmount());
        BigDecimal actualAmount = withdrawDTO.getAmount().subtract(fee);

        // 7. 记录钱包交易（提现申请）
        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransactionNo(generateTransactionNo());
        transaction.setUserId(userId);
        transaction.setWalletId(wallet.getId());
        transaction.setTransactionType("WITHDRAW");
        transaction.setAmount(withdrawDTO.getAmount());
        transaction.setBalanceBefore(wallet.getBalance());
        transaction.setBalanceAfter(wallet.getBalance().subtract(withdrawDTO.getAmount()));
        transaction.setTransactionStatus(3); // 处理中
        transaction.setDescription("申请提现");
        transaction.setRemark(String.format("提现到%s: %s", 
                withdrawDTO.getWithdrawMethod(), withdrawDTO.getAccountNo()));
        transaction.setCreatedTime(LocalDateTime.now());
        transaction.setUpdatedTime(LocalDateTime.now());
        walletTransactionMapper.insert(transaction);

        // 8. 构建返回结果
        WalletWithdrawResultVO result = new WalletWithdrawResultVO();
        result.setWithdrawId(transaction.getId());
        result.setWithdrawNo(transaction.getTransactionNo());
        result.setWithdrawAmount(withdrawDTO.getAmount());
        result.setFee(fee);
        result.setActualAmount(actualAmount);
        result.setWithdrawMethod(withdrawDTO.getWithdrawMethod());
        result.setWithdrawMethodDesc(getWithdrawMethodDesc(withdrawDTO.getWithdrawMethod()));
        result.setAccountNo(withdrawDTO.getAccountNo());
        result.setAccountName(withdrawDTO.getAccountName());
        result.setBankName(withdrawDTO.getBankName());
        result.setWithdrawStatus("PENDING");
        result.setWithdrawStatusDesc("提现申请已提交，等待处理");
        result.setApplyTime(LocalDateTime.now());
        result.setEstimatedArrivalTime(LocalDateTime.now().plusDays(1)); // 预计1天到账
        result.setRemark("提现申请已提交，我们将在1个工作日内处理");

        log.info("提现申请成功 - 用户: {}, 提现金额: {}, 手续费: {}, 实际到账: {}", 
                userId, withdrawDTO.getAmount(), fee, actualAmount);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean walletPayment(Long userId, BigDecimal amount, Long orderId, String payPassword, String description) {
        log.info("钱包支付 - 用户: {}, 金额: {}, 订单: {}", userId, amount, orderId);

        // 1. 验证支付密码
        if (!verifyPayPassword(userId, payPassword)) {
            throw new BusinessException(ResultCode.PASSWORD_ERROR);
        }

        // 2. 检查钱包余额
        UserWallet wallet = getOrCreateUserWallet(userId);
        BigDecimal availableBalance = wallet.getBalance().subtract(wallet.getFrozenAmount());
        if (availableBalance.compareTo(amount) < 0) {
            throw new BusinessException(ResultCode.BALANCE_NOT_ENOUGH);
        }

        // 3. 扣减余额
        BigDecimal balanceBefore = wallet.getBalance();
        BigDecimal balanceAfter = balanceBefore.subtract(amount);

        wallet.setBalance(balanceAfter);
        wallet.setTotalConsumption(wallet.getTotalConsumption().add(amount));
        wallet.setLastTransactionTime(LocalDateTime.now());
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        // 4. 记录钱包交易
        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransactionNo(generateTransactionNo());
        transaction.setUserId(userId);
        transaction.setWalletId(wallet.getId());
        transaction.setTransactionType("CONSUMPTION");
        transaction.setAmount(amount);
        transaction.setBalanceBefore(balanceBefore);
        transaction.setBalanceAfter(balanceAfter);
        transaction.setOrderId(orderId);
        transaction.setTransactionStatus(1); // 成功
        transaction.setDescription(description);
        transaction.setCreatedTime(LocalDateTime.now());
        transaction.setUpdatedTime(LocalDateTime.now());
        walletTransactionMapper.insert(transaction);

        log.info("钱包支付成功 - 用户: {}, 支付金额: {}, 余额: {} -> {}", 
                userId, amount, balanceBefore, balanceAfter);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean walletRefund(Long userId, BigDecimal amount, Long orderId, String description) {
        log.info("钱包退款 - 用户: {}, 金额: {}, 订单: {}", userId, amount, orderId);

        // 1. 获取钱包
        UserWallet wallet = getOrCreateUserWallet(userId);

        // 2. 增加余额
        BigDecimal balanceBefore = wallet.getBalance();
        BigDecimal balanceAfter = balanceBefore.add(amount);

        wallet.setBalance(balanceAfter);
        wallet.setTotalRefund(wallet.getTotalRefund().add(amount));
        wallet.setLastTransactionTime(LocalDateTime.now());
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        // 3. 记录钱包交易
        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransactionNo(generateTransactionNo());
        transaction.setUserId(userId);
        transaction.setWalletId(wallet.getId());
        transaction.setTransactionType("REFUND");
        transaction.setAmount(amount);
        transaction.setBalanceBefore(balanceBefore);
        transaction.setBalanceAfter(balanceAfter);
        transaction.setOrderId(orderId);
        transaction.setTransactionStatus(1); // 成功
        transaction.setDescription(description);
        transaction.setCreatedTime(LocalDateTime.now());
        transaction.setUpdatedTime(LocalDateTime.now());
        walletTransactionMapper.insert(transaction);

        log.info("钱包退款成功 - 用户: {}, 退款金额: {}, 余额: {} -> {}", 
                userId, amount, balanceBefore, balanceAfter);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setPayPassword(Long userId, String payPassword) {
        log.info("用户{}设置支付密码", userId);

        UserWallet wallet = getOrCreateUserWallet(userId);
        
        if (wallet.getHasPayPassword() == 1) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "支付密码已设置，请使用修改功能");
        }

        String encryptedPassword = BCrypt.hashpw(payPassword, BCrypt.gensalt());
        wallet.setPayPassword(encryptedPassword);
        wallet.setHasPayPassword(1);
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        log.info("用户{}支付密码设置成功", userId);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changePayPassword(Long userId, String oldPayPassword, String newPayPassword) {
        log.info("用户{}修改支付密码", userId);

        UserWallet wallet = getOrCreateUserWallet(userId);
        
        if (wallet.getHasPayPassword() != 1) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "尚未设置支付密码");
        }

        // 验证旧密码
        if (!BCrypt.checkpw(oldPayPassword, wallet.getPayPassword())) {
            throw new BusinessException(ResultCode.PASSWORD_ERROR.getCode(), "原支付密码错误");
        }

        // 设置新密码
        String encryptedPassword = BCrypt.hashpw(newPayPassword, BCrypt.gensalt());
        wallet.setPayPassword(encryptedPassword);
        wallet.setUpdatedTime(LocalDateTime.now());
        userWalletMapper.updateById(wallet);

        log.info("用户{}支付密码修改成功", userId);
        return true;
    }

    @Override
    public boolean verifyPayPassword(Long userId, String payPassword) {
        UserWallet wallet = getOrCreateUserWallet(userId);
        
        if (wallet.getHasPayPassword() != 1 || StrUtil.isBlank(wallet.getPayPassword())) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "尚未设置支付密码");
        }

        return BCrypt.checkpw(payPassword, wallet.getPayPassword());
    }

    @Override
    public PageResult<WalletTransactionVO> getWalletTransactions(Long userId, int page, int size) {
        log.info("查询用户{}钱包交易记录 - 页码: {}, 页大小: {}", userId, page, size);

        UserWallet wallet = getOrCreateUserWallet(userId);

        Page<WalletTransaction> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<WalletTransaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WalletTransaction::getWalletId, wallet.getId())
                .orderByDesc(WalletTransaction::getCreatedTime);

        Page<WalletTransaction> result = walletTransactionMapper.selectPage(pageParam, wrapper);

        List<WalletTransactionVO> records = result.getRecords().stream()
                .map(this::convertToWalletTransactionVO)
                .collect(Collectors.toList());

        return new PageResult<>(records, result.getTotal(), (int) result.getCurrent(), (int) result.getSize());
    }

    @Override
    public WalletSummaryVO getWalletSummary(Long userId) {
        log.info("获取用户{}钱包统计信息", userId);

        UserWallet wallet = getOrCreateUserWallet(userId);
        
        WalletSummaryVO summary = new WalletSummaryVO();
        summary.setUserId(userId);
        summary.setCurrentBalance(wallet.getBalance());
        summary.setTotalRecharge(wallet.getTotalRecharge());
        summary.setTotalConsumption(wallet.getTotalConsumption());
        summary.setTotalRefund(wallet.getTotalRefund());

        // 统计今日和本月交易
        LocalDate today = LocalDate.now();
        LocalDate monthStart = today.withDayOfMonth(1);

        LambdaQueryWrapper<WalletTransaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WalletTransaction::getWalletId, wallet.getId())
                .eq(WalletTransaction::getTransactionStatus, 1); // 成功的交易

        List<WalletTransaction> transactions = walletTransactionMapper.selectList(wrapper);

        BigDecimal todayIncome = BigDecimal.ZERO;
        BigDecimal todayExpense = BigDecimal.ZERO;
        BigDecimal monthIncome = BigDecimal.ZERO;
        BigDecimal monthExpense = BigDecimal.ZERO;
        BigDecimal pendingWithdraw = BigDecimal.ZERO;

        int rechargeCount = 0;
        int consumptionCount = 0;
        int refundCount = 0;
        int withdrawCount = 0;

        for (WalletTransaction txn : transactions) {
            LocalDate txnDate = txn.getCreatedTime().toLocalDate();
            
            // 统计次数
            switch (txn.getTransactionType()) {
                case "RECHARGE":
                    rechargeCount++;
                    break;
                case "CONSUMPTION":
                    consumptionCount++;
                    break;
                case "REFUND":
                    refundCount++;
                    break;
                case "WITHDRAW":
                    withdrawCount++;
                    if (txn.getTransactionStatus() == 3) { // 处理中
                        pendingWithdraw = pendingWithdraw.add(txn.getAmount());
                    }
                    break;
            }

            // 统计今日交易
            if (txnDate.equals(today)) {
                if ("RECHARGE".equals(txn.getTransactionType()) || "REFUND".equals(txn.getTransactionType())) {
                    todayIncome = todayIncome.add(txn.getAmount());
                } else if ("CONSUMPTION".equals(txn.getTransactionType()) || "WITHDRAW".equals(txn.getTransactionType())) {
                    todayExpense = todayExpense.add(txn.getAmount());
                }
            }

            // 统计本月交易
            if (!txnDate.isBefore(monthStart)) {
                if ("RECHARGE".equals(txn.getTransactionType()) || "REFUND".equals(txn.getTransactionType())) {
                    monthIncome = monthIncome.add(txn.getAmount());
                } else if ("CONSUMPTION".equals(txn.getTransactionType()) || "WITHDRAW".equals(txn.getTransactionType())) {
                    monthExpense = monthExpense.add(txn.getAmount());
                }
            }
        }

        summary.setTodayIncome(todayIncome);
        summary.setTodayExpense(todayExpense);
        summary.setMonthIncome(monthIncome);
        summary.setMonthExpense(monthExpense);
        summary.setPendingWithdraw(pendingWithdraw);
        summary.setRechargeCount(rechargeCount);
        summary.setConsumptionCount(consumptionCount);
        summary.setRefundCount(refundCount);
        summary.setWithdrawCount(withdrawCount);

        return summary;
    }

    /**
     * 获取或创建用户钱包
     */
    private UserWallet getOrCreateUserWallet(Long userId) {
        LambdaQueryWrapper<UserWallet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserWallet::getUserId, userId);
        UserWallet wallet = userWalletMapper.selectOne(wrapper);

        if (wallet == null) {
            // 创建新钱包
            wallet = new UserWallet();
            wallet.setUserId(userId);
            wallet.setBalance(BigDecimal.ZERO);
            wallet.setFrozenAmount(BigDecimal.ZERO);
            wallet.setTotalRecharge(BigDecimal.ZERO);
            wallet.setTotalConsumption(BigDecimal.ZERO);
            wallet.setTotalRefund(BigDecimal.ZERO);
            wallet.setWalletStatus(1); // 正常
            wallet.setHasPayPassword(0); // 未设置
            wallet.setCreatedTime(LocalDateTime.now());
            wallet.setUpdatedTime(LocalDateTime.now());
            userWalletMapper.insert(wallet);
            
            log.info("为用户{}创建新钱包", userId);
        }

        return wallet;
    }

    /**
     * 创建虚拟充值订单
     */
    private RentalOrder createVirtualRechargeOrder(Long userId, BigDecimal amount) {
        // TODO: 这里应该插入到数据库，但为了简化，暂时返回虚拟订单
        RentalOrder order = new RentalOrder();
        order.setId(System.currentTimeMillis()); // 临时ID
        order.setOrderNo("RECHARGE" + System.currentTimeMillis());
        order.setUserId(userId);
        order.setTotalAmount(amount);
        order.setOrderStatus(1);
        order.setCreatedTime(LocalDateTime.now());
        return order;
    }

    /**
     * 检查单日提现限额
     */
    private void checkDailyWithdrawLimit(Long userId, BigDecimal amount) {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();

        LambdaQueryWrapper<WalletTransaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WalletTransaction::getUserId, userId)
                .eq(WalletTransaction::getTransactionType, "WITHDRAW")
                .between(WalletTransaction::getCreatedTime, startOfDay, endOfDay);

        List<WalletTransaction> todayWithdraws = walletTransactionMapper.selectList(wrapper);
        BigDecimal todayWithdrawAmount = todayWithdraws.stream()
                .map(WalletTransaction::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        if (todayWithdrawAmount.add(amount).compareTo(MAX_DAILY_WITHDRAW) > 0) {
            throw new BusinessException(ResultCode.DAILY_WITHDRAW_LIMIT_EXCEEDED.getCode(), 
                    "超过单日提现限额" + MAX_DAILY_WITHDRAW + "元");
        }
    }

    /**
     * 计算提现手续费
     */
    private BigDecimal calculateWithdrawFee(BigDecimal amount) {
        // 简单的手续费计算：固定2元手续费，最小1元
        BigDecimal feeRate = new BigDecimal("0.002"); // 0.2%
        BigDecimal fee = amount.multiply(feeRate);
        BigDecimal minFee = new BigDecimal("1.00");
        BigDecimal maxFee = new BigDecimal("10.00");
        
        if (fee.compareTo(minFee) < 0) {
            fee = minFee;
        } else if (fee.compareTo(maxFee) > 0) {
            fee = maxFee;
        }
        
        return fee;
    }

    /**
     * 生成交易号
     */
    private String generateTransactionNo() {
        return "TXN" + System.currentTimeMillis() + RandomUtil.randomLong(1000, 9999);
    }

    /**
     * 获取钱包状态描述
     */
    private String getWalletStatusDesc(Integer walletStatus) {
        switch (walletStatus) {
            case 1:
                return "正常";
            case 2:
                return "冻结";
            case 3:
                return "关闭";
            default:
                return "未知";
        }
    }

    /**
     * 获取提现方式描述
     */
    private String getWithdrawMethodDesc(String withdrawMethod) {
        switch (withdrawMethod) {
            case "BANK_CARD":
                return "银行卡";
            case "ALIPAY":
                return "支付宝";
            default:
                return "未知";
        }
    }

    /**
     * 转换为钱包交易VO
     */
    private WalletTransactionVO convertToWalletTransactionVO(WalletTransaction transaction) {
        WalletTransactionVO vo = new WalletTransactionVO();
        BeanUtils.copyProperties(transaction, vo);
        vo.setTransactionTypeDesc(getTransactionTypeDesc(transaction.getTransactionType()));
        vo.setTransactionStatusDesc(getTransactionStatusDesc(transaction.getTransactionStatus()));
        return vo;
    }

    /**
     * 获取交易类型描述
     */
    private String getTransactionTypeDesc(String transactionType) {
        switch (transactionType) {
            case "RECHARGE":
                return "充值";
            case "CONSUMPTION":
                return "消费";
            case "REFUND":
                return "退款";
            case "WITHDRAW":
                return "提现";
            default:
                return "未知";
        }
    }

    /**
     * 获取交易状态描述
     */
    private String getTransactionStatusDesc(Integer transactionStatus) {
        switch (transactionStatus) {
            case 1:
                return "成功";
            case 2:
                return "失败";
            case 3:
                return "处理中";
            default:
                return "未知";
        }
    }
}